package mall.service;

import mall.pojo.ProductDO;
import mall.utils.ProductJudgeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车服务
 * @author zmy
 */
public class ShopCarService {
    private final List<ProductDO> shopCar = new ArrayList<>();
    private final ShelfService shelfService;

    private static volatile ShopCarService instance;
    private ShopCarService(ShelfService shelfService) {
        this.shelfService = shelfService;
    }
    public static ShopCarService getInstance(ShelfService shelfService) {
        if (instance == null) {
            synchronized (ShopCarService.class) {
                if (instance == null) {
                    instance = new ShopCarService(shelfService);
                }
            }
        }
        return instance;
    }


    /** 查看购物车详情，顺带返回购物车清单 */
    public List<ProductDO> showCar() {
        shopCar.forEach(product -> {
            System.out.println(shelfService.getProductById(product.getId()) + "活动价：" + product.getPrice());
        });
        System.out.println();
        return shopCar;
    }

    /**
     * 添加商品到购物车
     * 如果已有商品，则添加数量
     * 没有添加商品，则新增商品到购物车
     * @param productId 要购买的商品id
     * @param count     购买数量
     */
    public void addShop(String productId, int count) {
        // 库存商品信息
        ProductDO shelfProduct = shelfService.getProductById(productId);
        ProductDO byId = getById(productId);
        if (byId != null) { // 购物车里已存在，则添加数量
            int resultQuantity = byId.getQuantity() + count;
            if (resultQuantity > shelfProduct.getQuantity()) {
                System.out.println("库存不足！");
                return;
            }
            byId.setQuantity(resultQuantity);
        } else {
            // 购买的商品信息
            ProductDO addProduct = new ProductDO(shelfProduct.getId(), shelfProduct.getName(), shelfProduct.getPrice(), count);
            // 购物车内没有，直接新增
            if (addProduct.getQuantity() > shelfProduct.getQuantity()) {
                System.out.println("库存不足！");
                return;
            }
            shopCar.add(addProduct);
        }
    }

    /**
     * 减少购物车购买的商品数量
     * @param productId 商品 id
     * @param count     减少的数量
     */
    public void delCarProduct(String productId, int count) {
        ProductDO byId = getById(productId);
        if (byId == null) {
            System.out.println("您还没有购买过此商品！");
        } else if (byId.getQuantity() <= count) {
            shopCar.remove(byId);
            System.out.println("抱歉，您减少的购物车商品的数量不足，已为您移除商品！");
        } else {
            byId.setQuantity(byId.getQuantity() - count);
        }
    }

    public ProductDO getById(String productId) {
        ProductDO product=null;
        for (ProductDO p : shopCar) {
            if (ProductJudgeUtil.equalsId(p, productId)) {
                product = p;
                break;
            }
        }
        return product;
    }
}
